import re
import asyncio
from functools import wraps
from concurrent.futures import Future, ThreadPoolExecutor
from Apis.do_main_plus import chief
from Apis import *
from distributed import MyZK as MZK

executor = ThreadPoolExecutor(2)

async def fetch():
    return jsonify(Success_Resp)

loop = asyncio.new_event_loop()

@api.route('/process/', methods=['get'])
async def process_fun():
    param_projectId = request.json['projectId']
    param_updateMembers = request.json['updateMembers']
    if isinstance(param_projectId, list) is False:
        resp = jsonify(wrongProjectIdType_Resp)
        return resp
    if isinstance(param_updateMembers, int) is False:
        resp = jsonify(wrongUpdateMembersType_Resp)
        return resp
    if param_updateMembers not in updateMembers:
        resp = jsonify(wrongUpdateMembers_Resp)
        return resp
    if len(param_projectId) == 0:
        param_projectId = ProjectIdListBase
    
    # 分布式锁
    # 获取锁，若获取不到，则加锁，否则退出
    zkClient = MZK()
    LockedPorjectIdList = []
    LockedProjectIdError = []
    for projectId in param_projectId:
        # 如果没有获取到锁，则加锁，否则退出
        projectId_isLocked = zkClient.getLock(projectId)
        if projectId_isLocked is False:
            LockedPorjectIdList.append(projectId)
        else:
            lockSuccess = zkClient.lock(projectId)
            if lockSuccess is False: # 加锁
                LockedProjectIdError.append(projectId)
    if len(LockedPorjectIdList) > 0 or len(LockedProjectIdError) > 0:
        LockedProjectIds = ",".join(LockedPorjectIdList)
        LockErrorProjectIds = ",".join(LockedProjectIdError)
        LockInfo = {
            "LockErrorMsg":f"locks create Error or Unreleaseed",
            "LockedProjectIds" : LockedProjectIds,
            "LockErrorProjectIds" : LockErrorProjectIds
        }
        ProjectIdisLocked_Resp['data'] = LockInfo
        ProjectIdisLocked_Resp = jsonify(ProjectIdisLocked_Resp)
        return ProjectIdisLocked_Resp
    
    zkClient.stop()
    args =[param_projectId,param_updateMembers]
    executor.submit(lambda p : chief(*p), args)
    
    
    Success_Resp['msg'] = f"项目 {param_projectId} 正在执行" 
    resp = jsonify(Success_Resp)
    return resp

if __name__ == '__main__':
    api.run(port=port, debug=True, host=host)